package com.zeei.ems.base.strToDate;

import com.zeei.ems.base.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 全局将string 转为date
 */
public class StringToDateConverter implements Converter<String, Date> {
    private static final String dateFormat = DateUtils.TIMEF_FORMAT;
    private static final String shortDateFormat = DateUtils.DATE_FORMAT;
    @Override
    public Date convert(String value) {
        if (StringUtils.isEmpty(value)){
            return null;
        }
        try {
            if(value.contains("-")) {
                SimpleDateFormat formatter;
                if(value.contains(":")) {
                    formatter = new SimpleDateFormat(dateFormat);
                }else {
                    formatter = new SimpleDateFormat(shortDateFormat);
                }

                return formatter.parse(value);
            }else if(value.matches("^\\d+$")) {
                Long lDate = new Long(value);
                return new Date(lDate);
            }
        }catch (Exception e){
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", value));
    }
}
